var Utils = require('../../utils/util');
// var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
// pages/detail.js
const config = require('../../utils/config.js')

const util = require('../../utils/util.js')
const app = getApp();

// var qqmapsdk = new QQMapWX({
// 	key: 'UDUBZ-OZQ3F-IGWJH-JVQLK-SI5J2-UPFAU' //在这里输入你在腾讯位置服务平台申请的KEY
// });
var timer;

Page({
	data: {
		device: 'back',
		flash: '',
		date: "",
		time: "",
		week: "",
		address: "",
		addressName: "",
		cameraWidth: 0,
		cameraHeight: 0,
		canvasWidth: 0,
		canvasHeight: 0,
		port: '',
		number: '',
		latitude: 0,
		longitude: 0,
		username:app.globalData.userInfo.username
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {
		const systemInfo = wx.getSystemInfoSync();
		const screenWidth = systemInfo.screenWidth;
		const screenHeight = systemInfo.screenHeight;
		const statusBarHeight = systemInfo.statusBarHeight;
		const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
		const cameraWidth = screenWidth;
		const cameraHeight = screenHeight - statusBarHeight - menuButtonInfo.height - (menuButtonInfo.top -
			systemInfo.statusBarHeight) * 2 - 90;

		console.log(systemInfo)
		this.setData({
			cameraWidth: cameraWidth,
			cameraHeight: cameraHeight
		});
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		console.log(options);
		this.setData({
			port: options.port,
			number: options.number,
			address:options.address
		})
		if(options.port){
			wx.setNavigationBarTitle({
				title: `集中器${options.number}端口${options.port}` + ' 拍照',
			})
		}else{
			wx.setNavigationBarTitle({
				title: `集中器${options.number}端口` + ' 拍照',
			})
		}

		this.getTime()
		// this.getLocation()
	},

	/**
	 * 获取当前时间
	 */
	getTime: function () {
		timer = setInterval(() => {
			let timeData = Utils.formatTime2()
			this.setData({
				date: timeData.date,
				time: timeData.time,
				week: timeData.week
			})
		}, 1000)
	},

	/**
	 * 图片安全检测
	 */
	checkImage: function (imageUrl) {
		//自己去接入一下
		return new Promise((resolve, reject) => {
			wx.request({
				url: checkApi,
				method: "POST",
				data: {
					image: imageUrl
				},
				success: res => {
					wx.hideLoading()
					resolve(res.data.errcode)
					if (res.data.errcode == 0) {} else if (res.data.errcode == 87014) {
						wx.showModal({
							title: '温馨提示',
							content: '您的照片存在违规内容，请规范本小程序使用。',
							showCancel: false,
							complete: (res) => {
								wx.reLaunch({
									url: '/pages/index/index',
								})
							}
						})
					} else {
						wx.showToast({
							title: '图片检测失败，请重试',
							success: () => {
								wx.reLaunch({
									url: '/pages/index/index',
								})
							}
						})
					}
				}
			})
		})
	},

	/**
	 * 拍摄事件
	 */
	takePhoto: function () {
		const ctx = wx.createCameraContext()
		const that = this;
		ctx.takePhoto({
			quality: 'normal',
			success: async (res) => {
				console.log(res)
				this.setData({
					canvasWidth: res.width,
					canvasHeight: res.height,
					tempImagePath: res.tempImagePath
				})
				// 先图片内容安全检测
				// let checkResult = await this.checkImage(imageUrl)
				// if(checkResult==0){}

				wx.showLoading({
					title: '图片上传中...',
				})
				if(timer){
					clearInterval(timer)
				}
				let addWatermark = await this.addWatermark(res.tempImagePath)
				console.log("addWatermark")
				console.log(addWatermark)
				wx.saveImageToPhotosAlbum({
					filePath: addWatermark, //图片文件路径
					success: function (data) {
						console.log('保存本地相冊成功')
						console.log(data)
					},
					// 接口调用失败的回调函数
					fail: function (err) {
						console.log('保存本地相冊失败')
						console.log(err)
					}
				})
				that.uploadImg(addWatermark)
			}
		})
		return
		wx.chooseMedia({
			count: 1,
			mediaType: ['image'],
			sourceType: ['album'],
			maxDuration: 30,
			camera: 'back',
			success:async (res)=> {
				console.log(res.tempFiles[0].tempFilePath)
				this.setData({
					canvasWidth: res.width,
					canvasHeight: res.height,
					tempImagePath: res.tempFiles[0].tempFilePath
				})
				// 先图片内容安全检测
				// let checkResult = await this.checkImage(imageUrl)
				// if(checkResult==0){}

				let addWatermark = await this.addWatermark(res.tempFiles[0].tempFilePath)
				console.log("addWatermark")
				console.log(addWatermark)
				that.uploadImg(addWatermark)
			}
		})
		return

	},
	uploadImg:function (currentPic){

		const that=this;
		let formData = {
			group:'concentrator_'+this.data.number+`${this.data.port?`_${this.data.port}`:''}`
		};
		wx.uploadFile({
			url: `${config.prefix}/images`,
			header: {
				"Content-Type": "multipart/form-data",
				"Authorization": `Bearer ${app.globalData.userInfo.token}`
			},
			filePath: currentPic,
			name: 'file',
			formData:formData,
			success (res){
				console.log(res)
				if (res.statusCode === 200) {
					// wx.clearStorage()
					wx.showToast({
						title: '上传图片成功',
						icon: 'success'
					})
					wx.hideLoading()
					let pages = getCurrentPages() // 获取当前页面栈
					let prevPage = pages[pages.length - 2] // 获取到上一层页面栈
					// 将数据设置到上一层的 data 中
					let data=JSON.parse(res.data)
					if(that.data.port){
						let prevPagePicArr = prevPage.data[`port${that.data.port}PicArr`]
						prevPagePicArr.push(data.data.path)
						prevPage.setData({
							[`port${that.data.port}PicArr`]: prevPagePicArr
						})
					}else{
						let prevPagePicArr = prevPage.data.concentratorPicArr
						prevPagePicArr.push(data.data.path)
						prevPage.setData({
							concentratorPicArr: prevPagePicArr
						})
					}

					// 返回上一页
					wx.navigateBack();

				}
			}
		})

	},
	/**
	 * 给图片添加水印
	 */
	addWatermark: function (imageUrl) {
		console.log(imageUrl)
		return new Promise((resolve, reject) => {
			// wx.showLoading({
			// 	title: '图片生成中...',
			// })
			const query = wx.createSelectorQuery();
			query.select('#canvas').fields({
				node: true,
				size: true
			}).exec((res) => {
				console.log(res)
				const canvas = res[0].node;
				const ctx = canvas.getContext('2d');

				const dpr = wx.getSystemInfoSync().pixelRatio;
				const {
					canvasWidth,
					canvasHeight
				} = this.data;
				canvas.width = canvasWidth * 1
				canvas.height = canvasHeight * 1
				ctx.scale(1, 1)
				let fontSize=Math.ceil(canvasWidth/21)
				console.log('fontSize',fontSize)
				// 绘制背景图片
				const image = canvas.createImage();
				image.onload = () => {
					ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);

					/*let data = [];
					if(this.data.port){
						data = [
							['拍摄人：', this.data.username],
							['集中器号：', this.data.number],
							['端子号：', this.data.port],
							['地 址：', this.data.address],
							['时 间：', ''+this.data.date + ' ' + this.data.time+' '+this.data.week],
						];
					}else{
						data = [
							['拍摄人：', this.data.username],
							['集中器号：', this.data.number],
							['地 址：', this.data.address],
							['时 间：', ''+this.data.date + ' ' + this.data.time+' '+this.data.week],
						];
					}*/
					ctx.font = `normal ${fontSize}px null`;
					ctx.fillStyle = '#ffffff';
					ctx.textBaseline = 'bottom';

					// 绘制地址
					ctx.fillText('地 址：'+this.data.address, fontSize, canvasHeight - fontSize);

					// 绘制时间
					ctx.fillText('时 间：'+this.data.date + ' ' + this.data.time+' '+this.data.week, fontSize, canvasHeight - fontSize*2.3);
					if(this.data.port){
						// 端子号
						ctx.fillText('端子号：'+this.data.port, fontSize, canvasHeight - fontSize*3.6);

						// 集中器号
						ctx.fillText('集中器号：'+this.data.number, fontSize, canvasHeight - fontSize*4.9);

						// 用户
						ctx.fillText('拍摄人：'+this.data.username, fontSize, canvasHeight - fontSize*6.2);
					}else{
						// 集中器号
						ctx.fillText('集中器号：'+this.data.number, fontSize, canvasHeight - fontSize*3.6);
						// 用户
						ctx.fillText('拍摄人：'+this.data.username, fontSize, canvasHeight - fontSize*4.9);
					}


			/*		const columnWidths = [fontSize*4, fontSize*18]; // 表格
					const rowHeight = fontSize*1.3; // 行高
					const borderWidth = 1; // 边框宽度
					for (let i = 0; i < data.length; i++) {
						for (let j = 0; j < data[i].length; j++) {
							const cellX = j === 0 ? 0 : columnWidths.reduce((accumulator, currentValue, idx) => { if (idx < j) { return accumulator + currentValue } else { return accumulator } }, 0);
							const cellY = i * rowHeight;
							const cellWidth = columnWidths[j];
							const cellHeight = rowHeight;

							// 绘制单元格边框
							ctx.strokeStyle = '#fff'; // 设置边框颜色为黑色
							ctx.lineWidth = borderWidth;
							ctx.strokeRect(cellX, cellY, cellWidth, cellHeight);

							// 绘制单元格内容
							ctx.fillStyle = '#fff'; // 设置文本颜色为黑色
							ctx.font = `normal ${fontSize}px null`;
							ctx.fillText(data[i][j], cellX , cellY); // 绘制文本内容
						}
					}*/



					wx.canvasToTempFilePath({
						canvas,
						success: (res) => {
							// wx.hideLoading()
							resolve(res.tempFilePath);
						},
						fail: () => {
							wx.hideLoading()
							util.toastError('转换为图片失败');
							reject(new Error('转换为图片失败'));
						}
					});
				}
				image.src = imageUrl;
			});
		});
	},

	/**
	 * 切换摄像头
	 */
	setDevice: function () {
		this.setData({
			device: this.data.device == 'back' ? 'front' : 'back'
		})
		let text = this.data.device == 'back' ? '后置' : "前置";
		wx.showToast({
			title: "摄像头" + text
		})
	},

	/**
	 * 闪光灯开关
	 */
	setFlash: function () {
		this.setData({
			flash: this.data.flash == 'torch' ? 'off' : 'torch'
		})
	},

	/**
	 * 选择位置信息
	 */
	chooseLocation: function () {
		wx.chooseLocation({
			success: res => {
				console.log(res)
				this.setData({
					address: res.address
				})
			},
			fail: err => {
				console.log(err)
			}
		})

	},


	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	},
	onShareTimeline() {

	}
})